package com.cqtczh.qhd.driver.acticity;

import httptools.HttpJsonTool;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javabeen.UserInfoBeen;

import tools.L;
import tools.SD_Finder;


import cn.jpush.android.api.JPushInterface;

import com.google.gson.reflect.TypeToken;
import com.cqtczh.qhd.driver.AppContent;
import com.cqtczh.qhd.driver.R;
import com.cqtczh.qhd.driver.acticity.user.UserLoginActivity;
import com.cqtczh.qhd.driver.api.GagApi;
import com.cqtczh.qhd.driver.utils.Base64Util;
import com.cqtczh.qhd.driver.utils.CommonUtil;
import com.cqtczh.qhd.driver.utils.SPUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.ImageView;

/**
 * * @author 作者 陈修园:
 * 
 * @date 创建时间：2015-4-28 上午11:20:04
 * @version 1.0
 * @parameter
 * @since
 * @return
 */
public class New_MainActivity extends Activity {
	private boolean flag_teween = false;
	private boolean login_complete = false;
	private boolean exist_user = false;
	private AppContent app;
	private List<UserInfoBeen> userInfoBeens=new ArrayList<UserInfoBeen>();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_new_main);
		L.v("New_MainActivity", "New_MainActivity");
		app=(AppContent) getApplication();
		//L.v("出来1", "出来1");
		//L.v("出来2", "出来2");
		ImageView LOG_1 = (ImageView) findViewById(R.id.log);
		ImageView LOG_Word_2 = (ImageView) findViewById(R.id.med);
		AlphaAnimation log_anim = new AlphaAnimation(0, 1);
		AlphaAnimation LOG_Word_2_anim = new AlphaAnimation(0, 1);
		log_anim.setDuration(1000);
		LOG_Word_2_anim.setDuration(2500);
		LOG_Word_2_anim.setStartOffset(1500);
		LOG_Word_2_anim.setAnimationListener(new AnimationListener() {
			public void onAnimationStart(Animation arg0) {
			}
			public void onAnimationRepeat(Animation arg0) {
			}
			public void onAnimationEnd(Animation arg0) {
				flag_teween = true;
				JumpToNextActivity();
			}

		});
		LOG_1.setAnimation(log_anim);
		LOG_Word_2.setAnimation(LOG_Word_2_anim);
		log_anim.start();
		LOG_Word_2_anim.start();
		doCheckOldApp();
	}

	public void start() {
		if(appChecked){
			Start_PushMessage();
			Start_Gps();
			Start_User_Login();
			MakeFolder();
		}
	}

	public void MakeFolder(){
		String root=SD_Finder.GetPaht();
		if (root!=null) {
			//File.separator
		
		File file = new File(root+GagApi.TCZH_File);
		File TMP = new File(root+GagApi.IMAGE_FILE_PATH);
		File sound=new File(root+GagApi.SOUND_FILE_PATH);
		File file_apk=new File(root+GagApi.FILE_PATH);
		File UploadFile=new File(root+GagApi.UP_LOAD_FILE);
		// msg.obj=mBitmap;
		if (!file.exists()) {
			file.mkdir();
		//	 L.v("下载", "创建图片路径："+file.getPath());
		}
		if (!TMP.exists()) {
			TMP.mkdir();
		//	 L.v("下载",
	//		 "创建图片路径："+TMP.getPath());
		}
		if (!sound.exists()) {
			sound.mkdir();
		//	 L.v("下载",
		//			 "创建图片路径："+sound.getPath());
		}
		if (!file_apk.exists()) {
			file_apk.mkdir();
		}
		if (!UploadFile.exists()) {
			try {
				
				UploadFile.createNewFile();
				L.v("创建文件-->", UploadFile.getPath());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		}
	}
	
	
	public void Start_PushMessage() {
		JPushInterface.resumePush(getApplicationContext());
//		PushManager.getInstance().initialize(this.getApplicationContext());
//		JPushInterface.init(getApplicationContext());
	}
	
//	 
	
//	public void Start_PushMessage() {
//		PushManager.startWork(getApplicationContext(),
//				PushConstants.LOGIN_TYPE_API_KEY, "xGVLGuGeyehuEoNSxwRxFeEu");
		// L.d("请输入", "信息");
		/*
		 * 参数 layoutId ：自定义layout资源id layoutIconId ：自定义layout中显示icon 的id
		 * layoutTitleId ：自定义layout中显示标题的id layoutTextId ：自定义layout中显示内容的id
		 */

//		int layoutId = R.layout.notification_custom_builder;
//		int layoutIconId = R.id.notification_icon;
//		int layoutTitleId = R.id.notification_title;
//		int layoutTextId = R.id.notification_text;
//		CustomPushNotificationBuilder cBuilder = new CustomPushNotificationBuilder(
//				getApplicationContext(), layoutId, layoutIconId, layoutTitleId,
//				layoutTextId);
//		cBuilder.setNotificationFlags(Notification.FLAG_AUTO_CANCEL);
//		cBuilder.setNotificationDefaults(Notification.DEFAULT_SOUND
//				| Notification.DEFAULT_VIBRATE);
//		cBuilder.setStatusbarIcon(this.getApplicationInfo().icon);
//		cBuilder.setLayoutDrawable(R.drawable.ic_launcher);
//		PushManager.setNotificationBuilder(this, 1, cBuilder);
//	}

	public void Start_Gps() {

	}

	
	
	
	public void Start_User_Login() {
		String nameString = (String) SPUtils.get(this, "phone", "");
		String pswd = (String) SPUtils.get(this, "password", "");
	//	String password = (String) SPUtils.get(this, "driverPassword", "");
		pswd = Base64Util.fromHex(pswd);
		if ((nameString!=null)&&(nameString.length()>0)&&(pswd!=null)&&(pswd.length()>0)) {
			Map<String, Object> dataMap=new HashMap<String, Object>();
			exist_user = true;
			Type	type = new TypeToken<List<UserInfoBeen>>() {}.getType();
			L.v("username----------->",nameString);
			L.v("userpasswrod-------------->",pswd);
			dataMap.put("phone", nameString);
			dataMap.put("password", pswd);
			HttpJsonTool httpJsonTool=new HttpJsonTool(this,true);
			List<UserInfoBeen> data=new ArrayList<UserInfoBeen>();
			
			httpJsonTool.SetOnLister(new Handler(){
				@Override
				public void handleMessage(Message msg) {
					// TODO Auto-generated method stub
					super.handleMessage(msg);
					if (msg.what==1) {
						userInfoBeens=(List<UserInfoBeen>) msg.obj;
						
						//用户的ID
						app.userId=userInfoBeens.get(0).getCarownerid()+"";
						app.userInfoBeen=userInfoBeens.get(0);
						login_complete = true;
						JumpToNextActivity();
					}
				}
			});
			httpJsonTool.StartWork(dataMap, GagApi.LOGIN, type, null);
		}else {
			exist_user = false;
			JumpToNextActivity();
		}
		
	}

	private void JumpToNextActivity() {
		L.v("开始", "开始");
		L.v("login_complete", ""+login_complete);
		L.v("flag_teween", ""+flag_teween);
		L.v("exist_user", ""+exist_user);
		if(appChecked&&flag_teween){
			if (exist_user) {
				// TODO Auto-generated method stub
				if (login_complete) {
					L.v("跳转", "跳转");
					Intent intent = new Intent(this, ProjectHomeActivity.class);
					//Intent intent = new Intent(this, test.class);
					startActivity(intent);
					 this.finish();
				} else {
					Intent intent = new Intent(this, UserLoginActivity.class);
					startActivity(intent);
				    this.finish();
				}
			}else{
				Intent intent = new Intent(this, UserLoginActivity.class);
				startActivity(intent);
			    this.finish();
			}
		}
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		
		JPushInterface.onResume(this);
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		
		JPushInterface.onPause(this);
		super.onPause();
	}
	private boolean appChecked = true;
	private void doCheckOldApp(){
		final String oldPackage = "com.wonyesoft.wuliu.driver";
		if(CommonUtil.isAppInstalled(this, oldPackage)){
			appChecked = false;
			Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("检测到您的手机安装了旧版本的Q货的APP，强烈建议您删除旧版本APP");
			builder.setPositiveButton("卸载",new OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					Uri uri = Uri.parse("package:"+oldPackage);
					Intent uninstall = new Intent(Intent.ACTION_DELETE);
					uninstall.setData(uri);
					startActivityForResult(uninstall, 5555);
				}
			});
			builder.setCancelable(false);
			builder.show();
		}else{
			start();
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode == 5555){
			appChecked = true;
		}
		start();
	}
	
}
